package org.geektimes.projects.user.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import org.apache.commons.lang.StringUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.service.impl.UserServiceImpl;
import org.geektimes.web.mvc.controller.PageController;

/**
 * @Desc: 用户控制器
 * @author: liuawei
 * @date: 2021-03-01 16:39
 */
@Path("/register")
public class AuthController implements PageController {

    /**
     * 请求示例：
     *
     * 请求处理成功跳转成功页面 127.0.0.1:8080/register?name=evan&password=evanpassword
     * 请求处理失败跳转失败页面 127.0.0.1:8080/register?name=evan&password=
     * 
     * @param request
     *            HTTP 请求
     * @param response
     *            HTTP 相应
     * @return
     * @throws Throwable
     */
    @POST
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        // 参数校验
        if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
            return "login-form.jsp";
        }
        UserService userService = new UserServiceImpl();
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        if (userService.register(user)) {
            request.getServletContext().log("注册成功");
            return "registerSuccess.jsp";
        }
        return "registerFailed.jsp";
    }
}
